import { instance } from '@/common/ajax.js' // 全局挂载引入，配置相关在该index.js文件里修改

/**
 * 获取参数
 */
function getnavivalues() {
	var url = window.location.search; //获取url中"?"符后的字串
	url = url.split('#/')[0];
	var theRequest = new Array();
	if (url.indexOf('?') !== -1) {
		var str = url.substr(1);
		var strs = str.split('&');
		for (var i = 0; i < strs.length; i++) {
			theRequest[strs[i].split('=')[0]] = unescape(strs[i].split('=')[1]);
		}
	}
	return theRequest;
}

function roundFun(value, n) {
	return Math.round(value*Math.pow(10,n))/Math.pow(10,n);
}

/**
 * @param {Object} phone 点击打电话
 */
function clickCallPhone(phone) {
	if (isExist(phone) && phone.length >= 8) {
		var content = '是否拨打电话：' + phone;
		uni.showModal({
			title: '提示',
			content: content,
			success: function(res) {
				if (res.confirm) {
					uni.makePhoneCall({
						phoneNumber: phone //仅为示例
					});
				} else if (res.cancel) {
					console.log('用户点击取消');
				}
			}
		});
	} else {
		uni.showToast({
			title: '未有联系方式',
			duration: 1000,
			icon: 'none'
		});
		setTimeout(function() {
			uni.hideToast();
		}, 1000);
	}
}
	
function formatTime(time) {
	if (typeof time !== 'number' || time < 0) {
		return time
	}

	var hour = parseInt(time / 3600)
	time = time % 3600
	var minute = parseInt(time / 60)
	time = time % 60
	var second = time

	return ([hour, minute, second]).map(function(n) {
		n = n.toString()
		return n[1] ? n : '0' + n
	}).join(':')
}

function formatDateTime(date, fmt = 'yyyy-MM-dd hh:mm:ss') {
	if(!date) {
		return ''
	}
    if (typeof (date) === 'number') {
        date = new Date(date * 1000)
    }
    var o = {
        "M+": date.getMonth() + 1, //月份
        "d+": date.getDate(), //日
        "h+": date.getHours(), //小时
        "m+": date.getMinutes(), //分
        "s+": date.getSeconds(), //秒
        "q+": Math.floor((date.getMonth() + 3) / 3), //季度
        "S": date.getMilliseconds() //毫秒
    }
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length))
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)))
    return fmt
}

function formatLocation(longitude, latitude) {
	if (typeof longitude === 'string' && typeof latitude === 'string') {
		longitude = parseFloat(longitude)
		latitude = parseFloat(latitude)
	}

	longitude = longitude.toFixed(2)
	latitude = latitude.toFixed(2)

	return {
		longitude: longitude.toString().split('.'),
		latitude: latitude.toString().split('.')
	}
}

//坐标两点间距离
function rad(d) {
    return d * Math.PI / 180.0;
}
function getDistance(lng1, lat1, lng2, lat2) {
  var radLat1 = rad(lat1);
  var radLat2 = rad(lat2);
  var a = radLat1 - radLat2;
  var b = rad(lng1) - rad(lng2);
  var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
    + Math.cos(radLat1) * Math.cos(radLat2)
    * Math.pow(Math.sin(b / 2), 2)));
  s = s * 6378.137; //地球半径
  s = Math.round(s * 100) / 100;
  return s;//返回数值单位：公里
}
// 根据数组对象里元素排序
// 使用 arr.sort(compare('age'))
function compare(property){
    return function(a,b){
        var value1 = a[property];
        var value2 = b[property];
        return value1 - value2;
    }
}

var dateUtils = {
	UNITS: {
		'年': 31557600000,
		'月': 2629800000,
		'天': 86400000,
		'小时': 3600000,
		'分钟': 60000,
		'秒': 1000
	},
	humanize: function(milliseconds) {
		var humanize = '';
		for (var key in this.UNITS) {
			if (milliseconds >= this.UNITS[key]) {
				humanize = Math.floor(milliseconds / this.UNITS[key]) + key + '前';
				break;
			}
		}
		return humanize || '刚刚';
	},
	format: function(dateStr,noTime) {
		noTime=noTime||false
		var date = this.parse(dateStr)
		var diff = Date.now() - date.getTime();
		if (diff < this.UNITS['天']) {
			return this.humanize(diff);
		}
		var _format = function(number) {
			return (number < 10 ? ('0' + number) : number);
		};
		if(noTime){
				return date.getFullYear().toString().slice(2,4) + '-' + _format(date.getMonth() + 1) + '-' + _format(date.getDate());
			}else{
				return date.getFullYear() + '年' + _format(date.getMonth() + 1) + '月' + _format(date.getDate()) + ' ' +
						_format(date.getHours()) + ':' + _format(date.getMinutes());				
			}
	},
	parse: function(str) { //将"yyyy-mm-dd HH:MM:ss"格式的字符串，转化为一个Date对象
		var a = str.split(/[^0-9]/);
		return new Date(a[0], a[1] - 1, a[2], a[3], a[4], a[5]);
	}
};

//设置对象GPS信息
function setObjGpsInfo(obj,gps){
		if(gps.lat){
			obj.lat=gps.lat
			obj.lng=gps.lng
			
			obj.province=gps.province
			obj.provinceId=gps.provinceId
			obj.city=gps.city
			obj.cityId=gps.cityId
			obj.area=gps.area
			obj.areaId=gps.areaId
		}
}

function setObjAddressInfoByUserDetail(obj){
		let user_detail=uni.getStorageSync("user_detail")
		if(user_detail.id){
			obj.school=user_detail.school
			obj.schoolId=user_detail.schoolId						
			obj.academy=user_detail.academy						
			obj.academyId=user_detail.academyId
			obj.department=user_detail.department
			obj.departmentId=user_detail.departmentId
			obj.major=user_detail.major
			obj.majorId=user_detail.majorId
			obj.classes=user_detail.classes
			obj.classesId=user_detail.classesId
		}
}

function setObjAddressInfo(obj,address){
		if(address.id){
			obj.addressId=address.id
			obj.school=address.school
			obj.schoolId=address.schoolId						
			obj.academy=address.academy						
			obj.academyId=address.academyId
			obj.department=address.department
			obj.departmentId=address.departmentId
			obj.major=address.major
			obj.majorId=address.majorId
			obj.classes=address.classes
			obj.classesId=address.classesId
		}
}

function makeSchoolInfo(address,schools){
	return new Promise((resolve, reject) => {
		
		var result={}
		
		if(address.classesId!=null){			
			
			let schoolIdArray=[address.schoolId,address.academyId,address.departmentId,address.majorId,address.classesId]
			let schoolNameArray=[address.school,address.academy,address.department,address.major,address.classes]
			
			let schoolId=schoolIdArray[0]
			let schoolIndex=schools.findIndex((school)=>{
				return school.id==schoolId
			})					
			result.schoolIndex=schoolIndex
			
			result.schoolNow={id:schoolId,name:schoolNameArray[0]}
			
			let academyId=schoolIdArray[1]
			let departmentId=schoolIdArray[2]
			let majorId=schoolIdArray[3]
			let classesId=schoolIdArray[4]
			
			//获取学校信息
			instance.post('/Schoolacademy/search_by_ori_data',
				{schoolId:schoolId,academyId:academyId,departmentId:departmentId,majorId:majorId},
			).then(res => {
				if(res.status==200){
					let data=res.data
					let academies=[data.academies,data.departments,data.majors,data.classes]
					
					let academyIndex=data.academies.findIndex((item)=>{
						return item.id==academyId
					})
					let departmentIndex=data.departments.findIndex((item)=>{
						return item.id==departmentId
					})
					let majorIndex=data.majors.findIndex((item)=>{
						return item.id==majorId
					})
					let classesIndex=data.classes.findIndex((item)=>{
						return item.id==classesId
					})
					
					result.academies=academies
					result.academy=data.academies[academyIndex]
					result.department=data.departments[departmentIndex]
					result.major=data.majors[majorIndex]
					result.classes=data.classes[classesIndex]
					
					result.oldClassesIndex=classesIndex
					
					resolve(result)
				}else{
					reject(res.msg)
				}
			})
		}else{
			reject("地址信息不全")
		}
	})	
}


function tranGpsToRegin(gps){
	if(gps.province&&gps.provinceId>0){
		return {
			'code':[gps.provinceId,gps.cityId,gps.areaId],
			'region':[gps.province,gps.city,gps.area],
		}
	}else{
		return {
			'code':[110000,110100,110101],
			'region': ['北京市', '北京市', '东城区'],			
		}
	}
}

function tranReginToOri(ori,data){
		ori.provinceId=data.code[0];
		ori.province=data.region[0];
		ori.cityId=data.code[1];
		ori.city=data.region[1];
		ori.areaId=data.code[2];
		ori.area=data.region[2];
}

function isItemInList(list,key,item){
	let index=list.findIndex((obj)=>{
		return obj[key]==item
	})
	return index>-1
}

//百度地图转微信地图
function bMapTransWxMap(lng, lat) {
      let x_pi = 3.14159265358979324 * 3000.0 / 180.0;
      let x = lng - 0.0065;
      let y = lat - 0.006;
      let z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
      let theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
      let lngs = z * Math.cos(theta);
      let lats = z * Math.sin(theta);
      
      return {
          lng: lngs,
          lat: lats        
      }   
}

//微信地图转百度地图
function wxMapTransBMap(lng, lat) {
      let x_pi = 3.14159265358979324 * 3000.0 / 180.0;
      let x = lng;
      let y = lat;
      let z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
      let theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);
      let lngs = z * Math.cos(theta) + 0.0065;
      let lats = z * Math.sin(theta) + 0.006;
     
      return {
          lng: lngs,
          lat: lats 
      } 
}
//生成文字颜色
function calColor(dis){
	if(dis>=0&&dis<10){
		return "text-green";
	}
	if(dis>=11&&dis<30){
		return "text-olive";
	}
	if(dis>=31&&dis<50){
		return "text-cyan";
	}
	if(dis>=51&&dis<100){
		return "text-blue";
	}
	if(dis>=101){
		return "text-grey";
	}
}

module.exports = {
	formatTime,
	formatDateTime,
	formatLocation,
	dateUtils,
	getDistance,
	setObjGpsInfo,
	setObjAddressInfoByUserDetail,
	setObjAddressInfo,
	makeSchoolInfo,
	tranGpsToRegin,
	tranReginToOri,
	bMapTransWxMap,
	wxMapTransBMap,
	isItemInList,
	roundFun,
	calColor
}
